using System;
using System.Xml;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Resources;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;
using System.Reflection;
using Microsoft.SharePoint.Utilities;

namespace MacroView.SharePointFields
{
    public class BDCFieldControl : BaseFieldControl
    {

        protected Image imgDeleteSpacer;
        protected Image imgBrowseSpacer;
        protected TextBox txtBDCData;
        protected Label lblBDCData;
        protected PlaceHolder plhBDCViewScript;
        protected Literal phScript;
        protected ImageButton btnBrowse;
        protected ImageButton btnDelete;
        protected Boolean blnMultipleSelect = false;
        private int nSpacerWidth = 4;
        private int nTextBoxWidth = 300;
        private string sBDCApplication;
        private string sBDCReturnField;
        private string sDialogTitle;
        private string sManagedPropertyName;
        private string sBDCEntity;
        private string sBDCDisplayFields;

        public int TextBoxWidth
        {
            get
            {
                return nTextBoxWidth;
            }
            set
            {
                nTextBoxWidth = value;
            }
        }

        public int SpacerWidth
        {
            get
            {
                return nSpacerWidth;
            }
            set
            {
                nSpacerWidth = value;
            }
        }

        public string BDCApplication
        {
            get
            {
                return sBDCApplication;
            }
            set
            {
                sBDCApplication = value;
            }
        }

        public string BDCEntity
        {
            get
            {
                return sBDCEntity;
            }
            set
            {
                sBDCEntity = value;
            }
        }

        public string BDCDisplayFields
        {
            get
            {
                return sBDCDisplayFields;
            }
            set
            {
                sBDCDisplayFields = value;
            }
        }

        public string BDCReturnField
        {
            get
            {
                return sBDCReturnField;
            }
            set
            {
                sBDCReturnField = value;
            }
        }

        public string DialogTitle
        {
            get
            {
                return sDialogTitle;
            }
            set
            {
                sDialogTitle = value;
            }
        }

        protected override string DefaultTemplateName
        {
            get
            {
                return "BDCFieldControl";
            }
        }

        public override object Value
        {
            get
            {
                EnsureChildControls();
                return txtBDCData.Text;
            }

            set
            {
                EnsureChildControls();
                try
                {
                    txtBDCData.Text = (string)this.ItemFieldValue;
                    lblBDCData.Text = (string)this.ItemFieldValue;
                }
                catch { }
            }
        }

        public override void Focus()
        {

            EnsureChildControls();

        }
        protected override void OnPreRender(EventArgs e)
        {
            SPSite currentSite = null;
            SPWeb currentWeb = null;

            base.OnPreRender(e);

            try
            {
                if (!(txtBDCData == null))
                {
                    //if (txtBDCData.Text == "")
                    //{
                    //    btnDelete.ImageUrl = "/_layouts/images/blank.gif";
                    //    btnDelete.OnClientClick = "javascript:try { document.getElementById('" + txtBDCData.ClientID + @"').value='';document.getElementById('" + btnDelete.ClientID + @"').src='/_layouts/images/blank.gif';document.getElementById('" + btnBrowse.ClientID + @"').focus();return false; } catch (e) { alert(e.description); return false; }";
                    //}
                    //else
                    //{
                    //    btnDelete.ImageUrl = "/_layouts/images/delete.gif";
                    //    btnDelete.OnClientClick = "javascript:try { document.getElementById('" + txtBDCData.ClientID + @"').value='';document.getElementById('" + btnDelete.ClientID + @"').src='/_layouts/images/blank.gif';document.getElementById('" + btnBrowse.ClientID + @"').focus();return false; } catch (e) { alert(e.description); return false; }";
                    //}
                }
                else
                {
                    btnDelete.ImageUrl = "/_layouts/images/delete.gif";
                    btnDelete.OnClientClick = "javascript:try { document.getElementById('" + txtBDCData.ClientID + @"').value='';document.getElementById('" + btnDelete.ClientID + @"').src='/_layouts/images/blank.gif';document.getElementById('" + btnBrowse.ClientID + @"').focus();return false; } catch (e) { alert(e.description); return false; }";
                }

                currentWeb = SPContext.Current.Site.OpenWeb();

                plhBDCViewScript.Controls.Clear();
                phScript = new Literal();
                phScript.Text = @"<script>

            var ModalDialog = new Object;

            var ModalDialogWindow;
            var ModalDialogInterval;

            ModalDialog.value = '';
            ModalDialog.eventhandler = '';

            function ModalDialogMaintainFocus()
            {
              try
              {
                if (ModalDialogWindow.closed)
                 {
                    window.clearInterval(ModalDialogInterval);
                    eval(ModalDialog.eventhandler);       
                    return;
                 }
                ModalDialogWindow.focus(); 
              }
              catch (everything) {   }
            }
            
             function ModalDialogRemoveWatch()
             {
                ModalDialog.value = '';
                ModalDialog.eventhandler = '';
             }
            
             function BDCModalDialogShow(Title,URL,Buttons)
             {

               ModalDialogRemoveWatch();

               var args='width=450,height=450,left=325,top=300,toolbar=0,';
                   args+='location=0,status=0,menubar=0,scrollbars=0,resizable=0,titlebar=0';  

               ModalDialogWindow=window.open(URL,'',args); 

               ModalDialogWindow.focus(); 
               //ModalDialogInterval = window.setInterval('ModalDialogMaintainFocus()',5);

             }

            function MVDialog" + btnBrowse.ClientID + @"(defaultSearch)
                {

                    try
                        {
                            if(defaultSearch==undefined)
                                defaultSearch='';
                            
                            var sOldSelectedNode = new String(document.getElementById('" + txtBDCData.ClientID + @"').value);

                            //Replace Ampersands so they survive the url call.
                            sSelectedNode=sOldSelectedNode.replace(/&/g,'mvamp;');

                            var sDialogUrl = '" + currentWeb.Url + @"/_layouts/MVBDCLookUp.aspx?BDCApplication=" + Field.GetCustomProperty("Application").ToString() + @"&BDCReturnField=" + Field.GetCustomProperty("ReturnField").ToString() + @"&BDCEntity=" + Field.GetCustomProperty("Entity").ToString() + @"&ReturnField=" + txtBDCData.ClientID + @"&DisplayFields=" + SPEncode.UrlEncode(Field.GetCustomProperty("DisplayFields").ToString()) + @"';

                            var modalDialog=BDCModalDialogShow('" + sDialogTitle + @"',sDialogUrl,'');
                        }
                    catch (e)
                        {
                            alert('Error showing dialog. ' + sDialogUrl + ' ' + e.description);
                            return false;
                         }

                    return false;
                }

            </script>";

                plhBDCViewScript.Controls.Add(phScript);

                lblBDCData.Style["display"] = "none";

                //if (!ShowDeleteButton)
                //{
                //    btnDelete.Style["display"] = "none";
                //    imgDeleteSpacer.Style["display"] = "none";
                //}
            }
            catch (Exception ex)
            {
            }
            finally
            {
                //Destroy all the objects.
                if (currentWeb != null)
                {
                    currentWeb.Dispose();
                    currentWeb = null;
                }

                if (currentSite != null)
                {
                    currentSite.Dispose();
                    currentSite = null;
                }

            }

            plhBDCViewScript.Controls.Add(phScript);

        }

        protected override void CreateChildControls()
        {

            if (Field == null) return;

            base.CreateChildControls();

            if (ControlMode == Microsoft.SharePoint.WebControls.SPControlMode.Display)

                return;

            plhBDCViewScript = (PlaceHolder)TemplateContainer.FindControl("plhBDCViewScript");

            plhBDCViewScript = new PlaceHolder();
            this.Controls.Add(plhBDCViewScript);

            lblBDCData = new Label();
            lblBDCData.ID = this.ID + "lblBDCData";
            lblBDCData.CssClass = "ms-formlabel";
            this.Controls.Add(lblBDCData);

            txtBDCData = new TextBox();
            txtBDCData.ID = this.ID + "txtBDCData";
            txtBDCData.Style.Add("width", TextBoxWidth.ToString() + "px");
            txtBDCData.CssClass = "ms-input";
            txtBDCData.Width = TextBoxWidth;
            this.Controls.Add(txtBDCData);

            imgBrowseSpacer = new Image();
            imgBrowseSpacer.ImageUrl = "/_layouts/images/blank.gif";
            imgBrowseSpacer.Width = SpacerWidth;
            this.Controls.Add(imgBrowseSpacer);

            btnBrowse = new ImageButton();
            btnBrowse.ImageUrl = "/_layouts/images/addressbook.gif";
            btnBrowse.ID = this.ID + "btnBrowse";
            this.Controls.Add(btnBrowse);
            btnBrowse.OnClientClick = "javascript:return MVDialog" + btnBrowse.ClientID + "('');";

            //imgDeleteSpacer = new Image();
            //imgDeleteSpacer.ImageUrl = "/_layouts/images/blank.gif";
            //imgDeleteSpacer.Width = SpacerWidth;
            //this.Controls.Add(imgDeleteSpacer);

            //btnDelete = new ImageButton();
            //btnDelete.ID = this.ID + "btnDelete";
            //btnDelete.ImageUrl = "/_layouts/images/delete.gif";
            //this.Controls.Add(btnDelete);

        }

    }

}
